//
//  LoginViewController.m
//  XPhoto
//
//  Created by baboy on 2019/2/20.
//  Copyright © 2019 baboy. All rights reserved.
//

#import "LoginViewController.h"
#import "BKIndicator.h"
#import "User.h"
#import "RegisterViewController.h"
#import "BKNavigationController.h"
#import "VerificationCodeViewController.h"
#import <BKKit/BKApi.h>
#import <BKKit/UIViewController+x.h>

@interface LoginViewController ()<UITextFieldDelegate, VerificationCodeDelegate>

@end

@implementation LoginViewController
- (id)init{
    if (self = [super initWithNibName:NSStringFromClass([self class]) bundle:nil]){
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (IBAction)loginByPassword:(nullable id)button{
    NSString *userName = self.userNameTextField.text;
    NSString *password = self.passwordTextField.text;
    userName = userName ? [userName stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] : nil;
    if (!userName || userName.length == 0 || !password || password.length == 0) {
        [BKIndicator showMessageAndFadeOut:NSLocalizedString(@"username_or_pwd_should_not_be_null", @"提示") completion:nil];
        return;
    }
    //登陆
    [BKIndicator showMessage:NSLocalizedString(@"login_now", @"提示") ];
    [User loginWithUserName:userName
                   password:password
                   callback:^(id  _Nonnull task, User  *_Nullable user, NSError * _Nullable error) {
                       DLOG(@"");
                       if (error) {
                           [BKIndicator showMessageAndFadeOut:error.localizedDescription completion:^{
                               [self.passwordTextField becomeFirstResponder];
                           }];
                           return;
                       }
                       
                       [BKIndicator showMessageAndFadeOut:NSLocalizedString(@"login_success", @"提示") completion:nil];
                       [User login:user];
                       [User loginWithAuthToken: user.authToken];
                       [self.navigationController dismissViewControllerAnimated:YES completion:nil];
                   }];
}
- (IBAction)forgotPassword:(nullable id)button{
    
}

- (void)loginByMobile:(NSString *)mobile vcode:(NSString *) vcode{

    [BKIndicator showMessage:NSLocalizedString(@"login_now", @"提示")];
    [User loginWithMobile:mobile vcode:vcode callback:^(id  _Nonnull task, User *user, NSError * _Nullable error) {
        DLOG(@"");
        if (error) {
            [BKIndicator showMessageAndFadeOut:error.localizedDescription completion:^{
                
            }];
            return;
        }
        [BKIndicator showMessageAndFadeOut:NSLocalizedString(@"login_success", @"提示") completion:nil];
        [User login:user];
        [User loginWithAuthToken: user.authToken];
        [self.navigationController dismissViewControllerAnimated:YES completion:nil];
    }];
}
- (IBAction)signup:(nullable id)button{
    RegisterViewController *vc = [[RegisterViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}
- (IBAction)changeLoginTypeToVCode:(nullable id)button{
    [self.contentScrollView setContentOffset:CGPointMake(self.contentScrollView.bounds.size.width, 0) animated:YES];
}
- (IBAction)changeLoginTypeToPassword:(nullable id)button{
    [self.contentScrollView setContentOffset:CGPointZero animated:YES];
}

- (void)sendLoginSmsCode:(NSString *)mobile callback:(nullable void (^)( id _Nullable response,  NSError * _Nullable error))callback{
    [User sendLoginMobileVCode:mobile
                     callback:^(id  _Nonnull task, id  _Nullable response, NSError * _Nullable error) {
        if (error) {
            [BKIndicator showMessageAndFadeOut:error.localizedDescription completion:nil];
        }
        if(!error){
            [BKIndicator showMessageAndFadeOut:NSLocalizedString(@"vcode_send_success", @"提示") completion:nil];
        }
        if (callback) {
            callback(response, error);
        }
    }];
}
- (IBAction)loginByVCodeNextStep:(nullable id)button{
    BOOL ret = checkInput(@[
        @{
            @"field":self.mobileTextField,
            @"name":NSLocalizedString(@"mobile_no", @"标签"),
            @"min-len":@11,
            @"max-len":@11,
            @"regex":@"1[3-9]{1}\\d{9}"
        }], ^(NSString *errorMsg) {
        [BKIndicator showMessageAndFadeOut:errorMsg completion:nil];
    });
    if (!ret) {
        return;
    }
    
    NSString *mobile = self.mobileTextField.text;
    [self sendLoginSmsCode:mobile callback:^(id  _Nullable response, NSError * _Nullable error) {
        if (!error) {
            VerificationCodeViewController *vc = [[VerificationCodeViewController alloc] init];
            vc.mobile = mobile;
            vc.delegate = self;
            [self.navigationController pushViewController:vc animated:YES];
        }
    }];
}
#pragma UITextField Delegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    if (textField == self.userNameTextField) {
        NSString *text = textField.text?[textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]:nil;
        if (text && text.length>0) {
            [self.passwordTextField becomeFirstResponder];
        }
    }
    if (textField == self.passwordTextField) {
        [self loginByPassword:nil];
        [self.passwordTextField resignFirstResponder];
    }
    return YES;
}

#pragma mark - VerificationCodeDelegate
- (void)verificationCodeViewControllerWillResendVCode:(VerificationCodeViewController *)vc{
    [self sendLoginSmsCode:vc.mobile callback:nil];
}
- (void)verificationCodeViewController:(VerificationCodeViewController *)vc didInputVCode:(NSString *)vcode{
    [self loginByMobile:vc.mobile vcode:vcode];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
